package com.mingqijia.gassafety.shared.utils.bi;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gap.basic.exception.BizException;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Base64;

/**
 * 观远 bi调用
 * @author: duanhongxiang
 * @Desc:
 * @create: 2024-10-30 14:47
 **/
@Component
@Slf4j
public class BiRemoteService {
    @Value("${bi.login.id}")
    private String biLoginId ;

    @Value("${bi.login.password}")
    private String biLoginPassword ;

    @Value("${bi.login.domain}")
    private String biLoginDomain ;

    @Value("${bi.login.url}")
    private String biLoginUrl ;

    @Autowired
    RedisTemplate redisTemplate;

    public static final String getBiToken = "/public-api/sign-in";

    public static final String queryDataByPage = "/public-api/data-source/#{dsId}/data";

    /**
     * 获取Bi平台token
     * @return
     */
    public String getBiToken() {
        try {
            // 对字符串进行Base64编码
            String encodedString = Base64.getEncoder().encodeToString(biLoginPassword.getBytes());
            log.info("bi-getToken--原始字符串:{}", biLoginPassword);
            log.info("bi-getToken--Base64编码后的字符串:{}", encodedString);
            JSONObject json = new JSONObject();
            json.put("domain", biLoginDomain);
            json.put("loginId", biLoginId);
            json.put("password", encodedString);
            log.info("getBiToken-request:{}", JSONObject.toJSONString(json));
            String body = HttpUtil.doPostBody( JSONObject.toJSONString(json),biLoginUrl + getBiToken, "1123");
            log.info("getBiToken-resp:{}",body);
            JSONObject jsonResult= JSON.parseObject(body);
            if (jsonResult.containsKey("result") && jsonResult.getString("result").equals("ok")) {
                return jsonResult.getJSONObject("response").getString("token");
            } else {
                throw new BizException("获取bi平台token失败！");
            }
        } catch (Exception e) {
            log.error("获取bi平台token失败：{}", e.getMessage());
            throw new BizException(e.getMessage());
        }
    }

    public JSONObject queryDataByPage(String json, String biDataId, Integer count) {
        try {
            // 从Redis获取token
            String token = (String)redisTemplate.opsForValue().get(Constants.BI_TOKEN_KEY);
            if (StringUtils.isBlank(token)) {
                token = getBiToken();
                redisTemplate.opsForValue().set(Constants.BI_TOKEN_KEY, token);
            }
            String url = biLoginUrl + queryDataByPage.replace("#{dsId}", biDataId);
            log.info("queryDataByPage-url:{},request:{}, biDataId:{}", url, json, biDataId);
            String body = HttpRequest.post(url)
                    .header("Content-Type", "application/json")
                    .header("X-Auth-Token", token)
                    .body(json)
                    .execute()
                    .body();
            log.info("queryData-resp:{}",body);
            JSONObject jsonResult= JSON.parseObject(body);
            if (jsonResult.containsKey("result") && jsonResult.getString("result").equals("ok")) {
                return jsonResult.getJSONObject("response");
            } else if (jsonResult.containsKey("result") && jsonResult.getString("result").equals("fail")
                    && jsonResult.containsKey("error")){
                JSONObject errorResult = JSON.parseObject(jsonResult.getString("error"));
                if (errorResult.containsKey("status") && count < 3) {
                    // token过期了，重新获取token
                    String newToken = getBiToken();
                    // 将新token保存到redis
                    redisTemplate.opsForValue().set(Constants.BI_TOKEN_KEY, newToken);
                    // 再次调用方法
                    count++;
                    return queryDataByPage(json, biDataId, count);
                } else {
                    throw new BizException("查询bi平台数据集失败！");
                }
            } else {
                throw new BizException("查询bi平台数据集失败！");
            }
        } catch (Exception e) {
            log.error("查询bi平台数据集失败：{}", e.getMessage());
            throw new BizException(e.getMessage());
        }

    }

}
